
#include "stdafx.h"
using namespace System;
using namespace System::IO;

namespace GRIP
{
	namespace Cuda
	{
		void Logger::CheckCudaErrors(cudaError err, const char *file, const int line)
		{
			if(err != cudaSuccess)
			{
				String^ file_name = gcnew String(file);
				CudaException^ ex = gcnew CudaException(err, "CUDA Error in " + file_name + "(" + line + ").");
				WriteExceptionDetails(ex);
				throw ex;
			}
		}

		void Logger::CheckCudaErrors(CUresult err, const char *file, const int line)
		{
			if(err != cudaSuccess)
			{
				String^ file_name = gcnew String(file);
				CudaException^ ex = gcnew CudaException(err, "CUDA Error in " + file_name + "(" + line + ").");
				WriteExceptionDetails(ex);
				throw ex;
			}
		}

		void Logger::CheckDirectXErrors(HRESULT result, String^ message, const char *file, const int line)
		{
			if(FAILED(result))
			{
				String^ file_name = gcnew String(file);
				DirectXException^ ex = gcnew DirectXException(result, "DirectX Error in " + file_name + "(" + line + "): " + message);
				WriteExceptionDetails(ex);
				throw ex;
			}
		}

		void Logger::CheckCudaErrors(int err, const char *file, const int line)
		{
			if(FAILED(err))
			{
				String^ file_name = gcnew String(file);
				CudaException^ ex = gcnew CudaException(err, "CUDA Error in " + file_name + "(" + line + ").");
				WriteExceptionDetails(ex);
				throw ex;
			}
		}
		
		void Logger::Log(String^ message)
		{
			StreamWriter writer("error_native.log", true);
			writer.WriteLine(Environment::NewLine);
			writer.WriteLine(DateTime::Now);
			writer.WriteLine(message);
			writer.Close();
		}
		
		void Logger::WriteExceptionDetails(Exception^ ex)
		{
			StreamWriter writer("error_native.log", true);
			writer.WriteLine(Environment::NewLine);
			writer.WriteLine("----------------------");
			writer.WriteLine(DateTime::Now);
			writer.WriteLine("----------------------");
			writer.WriteLine(ex->Message);
			writer.WriteLine("----------------------");
			writer.WriteLine(System::Diagnostics::StackTrace(true).ToString());
			writer.Close();
		}
	}
}